const request = (url, method, data) => {
	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync('api_token');
		// uni.showLoading()
		uni.request({
			url: getApp().globalData.apiBase + url,
			method: method,
			data: data,
			header: {
				'content-type': 'application/json',
				'X-Auth-Token': token
			},
			success: res => {
				// uni.hideLoading()
				if (!res.data.code && res.statusCode == 200) {
					resolve(res.data);
				} else {
					if (token && res.statusCode == 403) {
						uni.removeStorageSync('api_token')
						uni.reLaunch({
							url: '/pages/index/login'
						})
					}
					if (token && res.data.message) {
						if (res.data.message == 'Username could not be found.') {
							uni.removeStorageSync('api_token')
							uni.reLaunch({
								url: '/pages/login/login'
							})
							return;
						}
						if (res.data.message == 'Entity is not found') {
							resolve(res.data);
							return;
						}
						if (res.data.message == 'User is not found or invalid password.') {
							uni.showModal({
								title: '提示',
								content: '登录账号/密码错误',
								showCancel: false
							})
							return;
						}
						// if (res.data.message == 'Error while generating verification code!') {
						// 	uni.showToast({
						// 		title: '获取短信失败',
						// 		icon: 'none'
						// 	})
						// 	// uni.hideLoading()
						// 	return;
						// }
						uni.showModal({
							title: '提示',
							content: res.data.message,
							showCancel: false
						})
					} else {
						if(res.data.message == '无绑定微信账号'){
							resolve(res.data);
							return
						}
						uni.showModal({
							title: '提示',
							content: res.data.message,
							showCancel: false
						})
						// uni.hideLoading()
						resolve(res.data);
						return;
					}

					reject(res.data.message);
				}
			},
			error: err => {
				reject('Network error');
			}
		})
	})
}

export default {
	get: (url, data) => request(url, 'GET', data),
	put: (url, data) => request(url, 'PUT', data),
	post: (url, data) => request(url, 'POST', data),
	delete: (url, data) => request(url, 'DELETE', data),
}
